import { UserItem, addUser, updateUser } from '@/services/user/user';
import type { ProFormInstance } from '@ant-design/pro-components';
import {
  ModalForm,
  ProFormSelect,
  ProFormText,
} from '@ant-design/pro-components';
import { message } from 'antd';
import { useRef } from 'react';

export type UserModalProps = {
  visible: boolean;
  onVisibleChange: (visible: boolean) => void;
  initialValues?: Partial<UserItem>;
  onSuccess: () => void;
};

const UserModal: React.FC<UserModalProps> = ({
  visible,
  onVisibleChange,
  initialValues,
  onSuccess,
}) => {
  const formRef = useRef<ProFormInstance>();

  return (
    <ModalForm<Omit<UserItem, 'id'>>
      formRef={formRef}
      title={initialValues ? '编辑用户' : '新增用户'}
      open={visible}
      onOpenChange={onVisibleChange}
      modalProps={{
        destroyOnClose: true,
        maskClosable: false,
      }}
      initialValues={initialValues}
      preserve={false}
      onFinish={async (values) => {
        try {
          let res;
          if (initialValues?.id) {
            res = await updateUser({ ...values, id: initialValues.id });
          } else {
            res = await addUser(values);
          }

          if (res.success) {
            message.success(`${initialValues ? '编辑' : '新增'}成功！`);
            onSuccess();
            return true;
          }
          return false;
        } catch (error) {
          message.error(`${initialValues ? '编辑' : '新增'}失败！`);
          return false;
        }
      }}
    >
      <ProFormText
        name="username"
        label="用户名"
        placeholder="请输入用户名"
        rules={[{ required: true, message: '请输入用户名' }]}
      />
      <ProFormText.Password
        name="password"
        label="密码"
        placeholder="请输入密码"
        rules={[{ required: true, message: '请输入密码' }]}
      />
      <ProFormText
        name="nickname"
        label="昵称"
        placeholder="请输入昵称"
        rules={[{ required: true, message: '请输入昵称' }]}
      />
      <ProFormText
        name="phone"
        label="手机号"
        placeholder="请输入手机号"
        rules={[{ required: true, message: '请输入手机号' }]}
      />
      <ProFormText
        name="email"
        label="邮箱"
        placeholder="请输入邮箱"
        rules={[{ required: true, message: '请输入邮箱' }]}
      />
      <ProFormSelect
        name="role"
        label="角色"
        placeholder="请选择角色"
        options={[
          { label: '管理员', value: 'admin' },
          { label: '普通用户', value: 'user' },
        ]}
        rules={[{ required: true, message: '请选择角色' }]}
      />
      <ProFormSelect
        name="status"
        label="状态"
        placeholder="请选择状态"
        options={[
          { label: '正常', value: 'active' },
          { label: '禁用', value: 'inactive' },
        ]}
        rules={[{ required: true, message: '请选择状态' }]}
      />
    </ModalForm>
  );
};

export default UserModal; 